<?php
/**
 * 后台公用抽象控制器。
 *
 * @author    Fairyin <fairyin@126.com>
 * @copyright © 2016 www.imcn.vip
 * @version   v1.0
 */

namespace App\Http\Controllers\Shadow;

require __DIR__.'/../../../../vendor/autoload.php';

use Cache;
use Cookie;
use Config;
use Request;
use Response;
use Redirect;
use Exception;
use Qiniu\Auth;
use App\Http\Model as MM;
use App\Http\Controllers\Controller;

abstract class ShadowController extends Controller
{
    /**
     * 当前登录对象。
     * @var mixed
     */
    protected $user;
    
    /**
     * 返回结果。
     * @var bool
     */
    protected $results;
    
    protected $qiniu_auth;
    
    const GET_LOVE = false;
    
    /**
     * redis缓存时间（默认：一天，单位：分钟）
     */
    const CACHE_LIFETIME = 120;

    public function __construct()
    {
        $s_token = isset($_COOKIE['u']) ? $_COOKIE['u'] : Request::get('u');
        $this->user = MM\User::checkToken($s_token);
        $this->results =  array(
            'debug' => Config('app.debug'),
            'version' => Config('app.version'),
            'last_version' => Config::get('app.last_version'),
            'loves' => $this->getLove(),
            'urls' => $this->getUrls()
        );
    }
    
    /**
     * ajax 失败的返回结果。
     * @param  array   $result  返回结果
     * @param  int     $code    状态码
     * @return mixed
     */
    public function ajaxError($result, $code = 403)
    {
        //todo memcached 监控请求，超次数限制
        return Response::json($result, $code);
    }
    
    /**
     * ajax 成功的返回结果。
     * @param  array   $result  返回结果
     * @param  int     $code    状态码
     * @return mixed
     */
    public function ajaxSuccess($result, $code = 200)
    {
        return Response::json($result, $code);
    }
    
    /**
     * 猜你喜欢。
     * @return array
     */
    public function getLove()
    {
        $a_results = array();
        if (static::GET_LOVE == false) {
            return $a_results;
        }
        $a_lists = $this->getAllLists();
        $i_start = count($a_lists);
        $i_start = rand(0, ($i_start - 4));
        $a_lists = array_slice($a_lists, $i_start, 4);
        if (count($a_lists)) {
            foreach ($a_lists as &$vv) {
                unset($vv['uid']);
                unset($vv['description']);
                unset($vv['type_id']);
                unset($vv['visit_times']);
                unset($vv['status']);
                unset($vv['create_time']);
                if (Config::get('app.env') == 'production') {
                    $vv['cover'] = $this->getBaseUrl($vv['cover'] . '-cover.jpg');
                }
            }
            shuffle($a_lists);
        }

        return $a_lists;
    }
    
    /**
     * 获取所有专辑数据并存入redis。
     * @return array
     */
    public function getAllLists()
    {
        $a_lists = array();
        if (Config::get('app.debug') == false && Cache::has('all_lists')) {
            $a_lists = json_decode(Cache::get('all_lists'), true);
            if (count($a_lists)) {
                return $a_lists;
            }
        }
        $a_lists = MM\Album::where('status', '=', 'show')->get()->toArray();
        if (count($a_lists)) {
            Cache::put('all_lists', json_encode($a_lists), static::CACHE_LIFETIME);
        }
        
        return $a_lists;
    }
    
    /**
     * 获取七牛云图床授权图片。
     * @param  string  $key 照片key
     * @return string
     */
    public function getBaseUrl($key, $public = true)
    {
        if ($public == true) {
            return Config::get('services.qiniu.host') . $key;
        }
        $accessKey = Config::get('services.qiniu.ak');
        $secretKey = Config::get('services.qiniu.sk');
        // 构建鉴权对象
        $o_auth = new Auth($accessKey, $secretKey);
        //baseUrl构造成私有空间的域名/key的形式
        $baseUrl = Config::get('services.qiniu.host') . $key;
        $authUrl = $o_auth->privateDownloadUrl($baseUrl);
        
        return $authUrl;
    }
    
    /**
     * 获取友链。
     * @return mixed
     */
    public function getUrls()
    {
        return MM\Url::where('status', '=', 'show')
            ->orderBy('weight', 'DESC')
            ->get()->toArray();
    }
}
